//
//  WYZ_SeekViewController.m
//  WYZ_YoungChat
//
//  Created by dllo on 16/3/17.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "WYZ_SeekViewController.h"
#import "WYZ_SeekModel.h"
#import "WYZ_DetailsViewController.h"
#import "WYZ_LookforCollectionCell.h"
#import "WYZ_LookTabelViewcell.h"
#import "ZYTokenManager.h"
#import "WYZ_HisCollectionViewcell.h"
@interface WYZ_SeekViewController ()<UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@property(nonatomic,retain)UISearchBar *searChBar;//搜索框
@property(nonatomic,retain)UITableView  *downTabelViw;//tabelView
@property(nonatomic,copy)NSString *str; //实时搜索名字
@property(nonatomic,copy)NSString *searStr;
@property(nonatomic,retain)NSMutableArray  *array;//装毛豆数组
@property(nonatomic,retain)UICollectionView *collection;//瀑布流
@property(nonatomic,retain)NSMutableArray  *arr;


@property(nonatomic,retain)NSArray *MutabeleArr;//搜索记录

@property(nonatomic,retain)UICollectionView *seekCollectionView;//搜索
@end

@implementation WYZ_SeekViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self  creatSearChBar]; //搜索框
    [self  createNavigation];//设置导航栏
    [self createCollection];//瀑布流
    [self creatTabelView];//创建tabelView;
    self.arr = [NSMutableArray arrayWithObjects:@"将夜",@"王家小姐",@"如果没有你",@"万妖之祖",@"沉香雪",@"三界血歌",@"盗墓笔记",@"侦探前传",@"锦衣夜行", nil];
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [super  viewWillAppear:animated];
    [self readNSUserDefaults];
    
    ///  如果数组没有保存的数据  就添加label
    if (self.MutabeleArr.count == 0)
    {
        UILabel *laa=[self.view viewWithTag:10000];
        UILabel *la  =[[UILabel alloc] init];
        [self.seekCollectionView addSubview:la];
        la.text =@"你还没有搜索记录";
        la.textAlignment = 1;
        la.textColor =[UIColor colorWithRed:1.000 green:0.520 blue:0.614 alpha:1.000];
        la.font = [UIFont systemFontOfSize:20*WIDTH];
        [la mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(laa.mas_bottom).offset(0);
            make.left.mas_equalTo(0);
            make.width.mas_equalTo(SCREEN_WIDTH);
            make.height.mas_equalTo(50);
        }];
    }
    
}
#pragma mark  设置导航栏
-(void)createNavigation
{
    self.view.backgroundColor =[UIColor whiteColor];
    self.navigationItem.titleView = self.searChBar;
    
    self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"qwe.png"] style:1 target:self action:@selector(barButton:)];
    self.navigationItem.leftBarButtonItem.tintColor =[UIColor blackColor];
    self.navigationController.navigationBar.barTintColor  = [UIColor colorWithRed:1.000 green:0.445 blue:0.525 alpha:1.000];
}
#pragma mark  瀑布流
-(void)createCollection
{
    
    UIButton *button =[UIButton buttonWithType:UIButtonTypeSystem];
    [self.view addSubview:button];
    [button setTitle:@"清空历史" forState:UIControlStateNormal];
    [button setTintColor:[UIColor colorWithWhite:0.320 alpha:1.000]];
    button.titleLabel.font =[UIFont systemFontOfSize:17*WIDTH];
    [button addTarget:self action:@selector(button) forControlEvents:UIControlEventTouchUpInside];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.width.mas_equalTo(100*WIDTH);
        make.height.mas_equalTo(50*HEIGHT);
    }];
    UILabel  *namelabel =[[UILabel alloc] init];
    namelabel.tag =10000;
    namelabel.text = @"历史记录";
    namelabel.font =[UIFont systemFontOfSize:17*WIDTH];
    [self.view addSubview:namelabel];
    [namelabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(10*WIDTH);
        make.width.mas_equalTo(100*WIDTH);
        make.height.mas_equalTo(50*HEIGHT);
    }];
    
    
    
    UICollectionViewFlowLayout *Layout = [[UICollectionViewFlowLayout alloc] init];
    Layout.itemSize =CGSizeMake(100*WIDTH, 25*HEIGHT);
    //这里对每一个用来显示的区域称为item,就是tableview上的cell
    //设置一下item的尺寸
    //通过设置flowlayout来设置样式
    //设置最小的行间距
    Layout.minimumInteritemSpacing =10*WIDTH;
    Layout.minimumLineSpacing=2*HEIGHT;
    Layout.scrollDirection =UICollectionViewScrollDirectionHorizontal;
    //设置flowlayout头部滚动de范围
    self.seekCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:Layout];
    [self.view addSubview:self.seekCollectionView];
    self.seekCollectionView.backgroundColor =[UIColor whiteColor];
    [self.seekCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(namelabel.mas_bottom).offset(0);
        make.left.mas_equalTo(0);
        make.width.mas_equalTo(SCREEN_WIDTH);
        make.height.mas_equalTo(50);
    }];
    [self.seekCollectionView registerClass:[WYZ_HisCollectionViewcell class] forCellWithReuseIdentifier:@"cell"];
    self.seekCollectionView.dataSource =self;
    self.seekCollectionView.delegate = self;
    
    
    
    
    UILabel *label =[[UILabel alloc] init];
    label.text = @"大家都在搜的:";
    label.textColor =[UIColor colorWithWhite:0.769 alpha:1.000];
    [self.view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.seekCollectionView.mas_bottom).offset(0);//20
        make.left.mas_equalTo(10*WIDTH);
        make.width.mas_equalTo(150*WIDTH);
        make.height.mas_equalTo(50*HEIGHT);
    }];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize =CGSizeMake(100*WIDTH, 25*HEIGHT);
    //这里对每一个用来显示的区域称为item,就是tableview上的cell
    //设置一下item的尺寸
    //通过设置flowlayout来设置样式
    //设置最小的行间距
    flowLayout.minimumInteritemSpacing =10*WIDTH;
    flowLayout.minimumLineSpacing=2*HEIGHT;
    flowLayout.sectionInset =UIEdgeInsetsMake(20*HEIGHT, 20*WIDTH, 50*HEIGHT,100*WIDTH); //距四周的距离
    //设置flowlayout头部滚动de范围
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:flowLayout];
    [self.view addSubview:self.collection];
    self.collection.backgroundColor =[UIColor whiteColor];
    [self.collection mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(label.mas_bottom).offset(0);
        make.left.mas_equalTo(0);
        make.width.mas_equalTo(SCREEN_WIDTH);
        make.height.mas_equalTo(SCREEN_HEIGHT);
    }];
    [self.collection registerClass:[WYZ_LookforCollectionCell class] forCellWithReuseIdentifier:@"LookforCollectionCell"];
    self.collection.dataSource =self;
    self.collection.delegate = self;
    
}
#pragma mark  清除历史记录
-(void)button
{
    /// 清楚历史记录
    [ZYTokenManager  removeAllArray];
    NSLog(@"装历史记录的数组==%@",self.MutabeleArr);
    
    /// 数组为空
    
    self.MutabeleArr = nil;
    [self.seekCollectionView reloadData];
    if (self.MutabeleArr.count == 0)
    {
        UILabel *laa=[self.view viewWithTag:10000];
        UILabel *la  =[[UILabel alloc] init];
        [self.seekCollectionView addSubview:la];
        la.text =@"你还没有搜索记录";
        la.textAlignment = 1;
        la.textColor =[UIColor colorWithRed:1.000 green:0.520 blue:0.614 alpha:1.000];
        la.font = [UIFont systemFontOfSize:20*WIDTH];
        [la mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(laa.mas_bottom).offset(0);
            make.left.mas_equalTo(0);
            make.width.mas_equalTo(SCREEN_WIDTH);
            make.height.mas_equalTo(50);
        }];
    }
    
}

#pragma mark 点击方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView ==self.collection)
    {
        WYZ_DetailsViewController  *dvc =[[WYZ_DetailsViewController alloc] init];
        [self.navigationController pushViewController:dvc animated:YES];
        if (indexPath.row == 0)
        {
            dvc.albumId = @"3581543";
        }else
            if (indexPath.row == 1)
            {
                dvc.albumId = @"3271139";
            }else
                if (indexPath.row == 2)
                {
                    dvc.albumId = @"3614370";
                }else
                    if (indexPath.row == 3)
                    {
                        dvc.albumId = @"3631177";
                    }else
                        if (indexPath.row == 4)
                        {
                            dvc.albumId = @"3580629";
                        }else
                            if (indexPath.row == 5)
                            {
                                dvc.albumId = @"3581692";
                            }else
                                if (indexPath.row == 6)
                                {
                                    dvc.albumId = @"3580629";
                                }else
                                    if (indexPath.row == 7)
                                    {
                                        dvc.albumId = @"3594776";
                                    }else
                                        if (indexPath.row == 8)
                                        {
                                            dvc.albumId = @"3144233";
                                        }
        
    }else
    {
        NSLog(@"进不去");
    }
}
#pragma mark  item大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.collection)
    {
        if ([self.arr[indexPath.row] length] == 2)
        {
            return CGSizeMake(50*WIDTH, 25*HEIGHT);
        }else
            if ([self.arr[indexPath.row] length] == 3)
            {
                return CGSizeMake(70*WIDTH, 25*HEIGHT);
            }else
                if ([self.arr[indexPath.row] length] == 4)
                {
                    return CGSizeMake(80*WIDTH, 25*HEIGHT);
                }else
                {
                    return CGSizeMake(100*WIDTH, 25*HEIGHT);
                }
        
    }else
    {
        if ([self.MutabeleArr[indexPath.row] length] == 2)
        {
            return CGSizeMake(50*WIDTH, 25*HEIGHT);
        }else
            if ([self.MutabeleArr[indexPath.row] length] == 3)
            {
                return CGSizeMake(70*WIDTH, 25*HEIGHT);
            }else
                if ([self.MutabeleArr[indexPath.row] length] == 4)
                {
                    return CGSizeMake(80*WIDTH, 25*HEIGHT);
                }else
                {
                    return CGSizeMake(100*WIDTH, 25*HEIGHT);
                }
        
    }
}
#pragma mark  几个item
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (collectionView == self.collection)
    {
        return self.arr.count;
    }else
    {
        return self.MutabeleArr.count;
    }
}
#pragma mark  创建cell
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.collection)
    {
        WYZ_LookforCollectionCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"LookforCollectionCell" forIndexPath:indexPath];
        cell.titleLabel.text = self.arr[indexPath.row];
        return cell;
    }else
    {
        WYZ_HisCollectionViewcell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
        cell.titLabel.text = self.MutabeleArr[indexPath.row];
        return cell;
    }
}


#pragma mark  searChar
-(void)creatSearChBar
{
    self.searChBar = [[UISearchBar alloc] initWithFrame:CGRectMake(70*WIDTH, 20*HEIGHT, 340*WIDTH,50*HEIGHT)];
    //边框颜色
    self.searChBar.barTintColor = [UIColor whiteColor];
    UITextField *searchField =[self.searChBar valueForKey:@"searchField"];
    //背景色
    [searchField setBackgroundColor:[UIColor whiteColor]];
    //输入字体颜色
    searchField.textColor = [UIColor colorWithRed:0.023 green:0.052 blue:0.062 alpha:1.000];
    //提示字
    searchField.placeholder=@"请输入您想搜索的内容";
    
    //通过@"_placeholderLabel.textColor" 找到placeholder的字体颜色
    [searchField setValue:[UIColor blackColor] forKeyPath:@"_placeholderLabel.textColor"];
    
    //圆角
    searchField.layer.cornerRadius =14.0f;
    searchField.layer.masksToBounds = YES;
    self.searChBar.delegate = self;
}
#pragma mark  时时搜索
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (![searchText hasPrefix:@" "]&&![searchText isEqualToString:@" "] && ![searchText hasSuffix:@" "]&& ![searchText containsString:@" "])
    {
        self.str = searchText;
        self.searStr = searchText;
        [self.view addSubview:self.downTabelViw];
        [self.downTabelViw  mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(0);
            make.left.mas_equalTo(0);
            make.width.mas_equalTo(SCREEN_WIDTH);
            make.height.mas_equalTo(SCREEN_HEIGHT);
        }];
        [self createParsing]; //数据解析
        [ZYTokenManager SearchText:searchText]; // nsuserdifui保存
        [self readNSUserDefaults];
    }else
    {
        [self.downTabelViw  removeFromSuperview]; //移除视图
    }
}
#warning mark  取出缓存的数据
-(void)readNSUserDefaults
{
    //取出缓存的数据
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    //读取数组NSArray类型的数据
    NSArray * myArray = [userDefaultes arrayForKey:@"myArray"];
    self.MutabeleArr = myArray;
    
    [self.seekCollectionView reloadData];
    NSLog(@"myArray======%@",self.MutabeleArr);
    
}

#warning mark  数据解析
-(void)createParsing
{
    
    // url一般有字母,数字和特殊的符号比如/,&,?,=,$组成,所以一般的url里没有汉子的,所有的汉子在请求的时候需要给他进行转码
    // ios9.0之后,转码的方法也发生了变化,采用字符集合的方式对网址进行转码操作
    self.str =[self.str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:self.str]];
    
    AFHTTPSessionManager *manger =[AFHTTPSessionManager manager];
    [manger.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", @"application/x-javascript", @"application/javascript",nil]];
    
    [manger GET:[NSString stringWithFormat:@"http://search.ximalaya.com/suggest?device=iPhone&kw=%@",self.str] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        self.array =[NSMutableArray array];
        for (NSDictionary *diction in responseObject[@"albumResultList"])
        {
            WYZ_SeekModel *mod =[[WYZ_SeekModel alloc] init];
            [mod setValuesForKeysWithDictionary:diction];
            [self.array  addObject:mod];
        }
        for (NSDictionary *diction in responseObject[@"queryResultList"])
        {
            WYZ_SeekModel *mod =[[WYZ_SeekModel alloc] init];
            [mod setValuesForKeysWithDictionary:diction];
            [self.array  addObject:mod];
        }
        
        [self.downTabelViw reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        UIAlertController * alert=[UIAlertController alertControllerWithTitle:@"网络延迟" message:@"网络重新连接中"preferredStyle:UIAlertControllerStyleAlert];
        //显示alertController
        [self presentViewController:alert animated:YES completion:^{}];
        //添加button
        UIAlertAction * action=[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alert addAction:action];
        
    }];
    
}
#pragma mark  tabeklView;
-(void)creatTabelView
{
    self.downTabelViw =[[UITableView alloc] init];
    self.downTabelViw.backgroundColor =[UIColor colorWithWhite:0.916 alpha:1.000];
    self.downTabelViw.rowHeight = 50*HEIGHT;
    self.downTabelViw.separatorColor =[UIColor whiteColor];
    self.downTabelViw.backgroundColor =[UIColor whiteColor];
    self.downTabelViw.dataSource = self;
    self.downTabelViw.delegate = self;
    [self.downTabelViw registerClass:[WYZ_LookTabelViewcell class] forCellReuseIdentifier:@"reuse"];
    [self.downTabelViw registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reus"];
}
#pragma mark 点击方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WYZ_SeekModel *model =self.array[indexPath.row];
    if ([model.category isEqualToString:@"有声书"])
    {
        WYZ_DetailsViewController *dvc =[[WYZ_DetailsViewController alloc] init];
        dvc.albumId = model.DLid;
        [self.navigationController  pushViewController:dvc animated:NO];
    }else
    {
        UIAlertController * alert=[UIAlertController alertControllerWithTitle:@"资料丢失啦" message:@"请稍后再试"preferredStyle:UIAlertControllerStyleAlert];
        //显示alertController
        [self presentViewController:alert animated:YES completion:^{}];
        //添加button
        UIAlertAction * action=[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alert addAction:action];
    }
    
}
#pragma mark 几个cell
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.array.count;
}
#pragma mark tabelView cell创建
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    WYZ_SeekModel *model =self.array[indexPath.row];
    if ([model.category  isEqualToString:@"有声书"])
    {
        WYZ_LookTabelViewcell *cell =[tableView dequeueReusableCellWithIdentifier:@"reuse"];
        [cell.picimageView setImageWithURL:[NSURL URLWithString:model.imgPath]];
        cell.leftLabel.text = model.keyword;
        cell.rightLabel.text = model.category;
        
        
        NSRange range = [cell.leftLabel.text rangeOfString:self.searStr];
        NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:model.keyword];
        //可以设置划线颜色与字体颜色,设置颜色范围;
        [attri addAttribute:NSForegroundColorAttributeName value:[UIColor redColor]range:range];
        //还可以设置某个字体大小
        [attri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:25.0*WIDTH] range:range];
        [ cell.leftLabel setAttributedText:attri];
        //   点击cell的效果
        cell.selectionStyle = UITableViewScrollPositionNone;
        return cell;
    }else
    {
        UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"reus"];
        cell.textLabel.text = model.keyword;
        NSRange range = [cell.textLabel.text rangeOfString:self.searStr];
        NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:model.keyword];
        //可以设置划线颜色与字体颜色,设置颜色范围;
        [attri addAttribute:NSForegroundColorAttributeName value:[UIColor redColor]range:range];
        //还可以设置某个字体大小
        [attri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:25.0*WIDTH] range:range];
        [ cell.textLabel setAttributedText:attri];
        //   点击cell的效果
        cell.selectionStyle = UITableViewScrollPositionNone;
        return cell;
    }
}

#pragma mark button  点击方法
-(void)barButton:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
